package com.andy.blog.generator.util;

import freemarker.template.Configuration;
import freemarker.template.DefaultObjectWrapper;
import freemarker.template.Template;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.FileWriter;
import java.nio.charset.StandardCharsets;

/**
 * freeMarker工具类
 * Created by andy on 2023/5/5 18:18
 */
public class FreeMarkerUtils {

    private static final Logger logger = LoggerFactory.getLogger(FreeMarkerUtils.class);

    /**
     * freemarker 填充模版文件
     *
     * @param writeFilePath 填充后的模版文件下载路径
     * @param templateName  模版文件名称
     * @param data          数据对象
     */
    public void fillTemplate(String writeFilePath, String templateName, Object data) {
        Configuration configuration = new Configuration(Configuration.getVersion());
        configuration.setDefaultEncoding(StandardCharsets.UTF_8.name());
        configuration.setClassForTemplateLoading(this.getClass(), "/ftl");
        configuration.setObjectWrapper(new DefaultObjectWrapper(Configuration.getVersion()));

        try (FileWriter fileWriter = new FileWriter(writeFilePath)) {
            Template template = configuration.getTemplate(templateName);
            template.process(data, fileWriter);
        } catch (Exception e) {
            logger.error("生成模版文件失败", e);
        }
    }
}
